/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.rocketmq.client.impl.consumer;

import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.client.log.ClientLogger;
import org.apache.rocketmq.common.ServiceThread;
import org.apache.rocketmq.common.protocol.RequestCode;
import org.apache.rocketmq.common.protocol.heartbeat.SubscriptionData;
import org.apache.rocketmq.common.utils.ThreadUtils;
import org.apache.rocketmq.logging.InternalLogger;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * consumer拉取mq消息的服务
 * <pre>
 * 拉消息: {@link RequestCode#PULL_MESSAGE}
 *
 *
 *     消息消费有两种模式：广播模式与集群模式，
 *     - 广播模式: 每一个消费者需要去拉取订阅主题下所有消费队列的消息。
 *     - 集群模式: 同一个消费组内有多个消息消费者，同一个主题存在多个消费队列，那么消费者如何进行消息队列负载呢？
 *         从上文启动流程也知道，每一个消费组内维护一个线程池来消费消息，那么这些线程又是如何分工合作的呢？
 *     - 消息队列负载，通常的做法是【一个消息队列在同一时间只允许被一个消息消费者消费，一个消息消费者可以同时消费多个消息队列】，那么RocketMQ是如何实现的呢？
 *     - RocketMQ使用一个单独的线程 —— PullMessageService 来负责消息的拉取。
 * </pre>
 */
public class PullMessageService extends ServiceThread {
    private final InternalLogger log = ClientLogger.getLog();

    /**
     * 存放 PullRequest拉取消息请求 的队列
     *
     * 新增: {@link #executePullRequestImmediately}
     * 处理: {@link #run()}
     *
     * 问题1: PullRequest对象在什么时候创建并加人到pullRequestQueue中以便唤醒PullMessageService 线程。
     *        1) 
     *        2) consumer从broker拉取请求的callback中:{@link DefaultMQPushConsumerImpl#newPullCallback}
     *
     */
    private final LinkedBlockingQueue<PullRequest> pullRequestQueue = new LinkedBlockingQueue<PullRequest>();

    private final MQClientInstance mQClientInstance;

    /**
     * 延迟线程池
     */
    private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "PullMessageServiceScheduledThread");
        }
    });

    public PullMessageService(MQClientInstance mQClientInstance) {
        this.mQClientInstance = mQClientInstance;
    }

    /**
     * 立即执行拉取请求
     */
    public void executePullRequestImmediately(final PullRequest pullRequest) {
        try {
            this.pullRequestQueue.put(pullRequest);
        } catch (InterruptedException e) {
            log.error("executePullRequestImmediately pullRequestQueue.put", e);
        }
    }

    /**
     * 稍后执行拉取请求
     * <p>
     * 其实就是使用 {@link #scheduledExecutorService} 延迟线程池,延迟一段时间后,调用 {@link #executePullRequestImmediately} 方法.
     *
     * @param pullRequest 拉取请求
     * @param timeDelay   延迟时间(单位:毫秒)
     */
    public void executePullRequestLater(final PullRequest pullRequest, final long timeDelay) {
        if (!isStopped()) {
            this.scheduledExecutorService.schedule(() -> executePullRequestImmediately(pullRequest), timeDelay, TimeUnit.MILLISECONDS);
        } else {
            log.warn("PullMessageServiceScheduledThread has shutdown");
        }
    }

    public void executeTaskLater(final Runnable r, final long timeDelay) {
        if (!isStopped()) {
            this.scheduledExecutorService.schedule(r, timeDelay, TimeUnit.MILLISECONDS);
        } else {
            log.warn("PullMessageServiceScheduledThread has shutdown");
        }
    }

    public ScheduledExecutorService getScheduledExecutorService() {
        return scheduledExecutorService;
    }

    /**
     * 拉消息
     *
     * 请求类型: {@link RequestCode#PULL_MESSAGE}
     */
    private void pullMessage(final PullRequest pullRequest) {
        // 根据消费者组,选择出一个consumer.去拉取请求
        final MQConsumerInner consumer = this.mQClientInstance.selectConsumer(pullRequest.getConsumerGroup());
        if (consumer != null) {
            // 令人意外的是这里将consumer强制转换为DefaultMQPushConsumerlmpl,也就是PullMessageService,
            // 该线程只为PUSH模式服务,那拉模式如何拉取消息呢? PULL模式, RocketMQ只需要提供拉取消息API即可,具体由应用程序显示调用拉取API。
            ((DefaultMQPushConsumerImpl) consumer).pullMessage(pullRequest);
        } else {
            log.warn("No matched consumer for the PullRequest {}, drop it", pullRequest);
        }
    }

    @Override
    public void run() {
        log.info(this.getServiceName() + " service started");

        while (!this.isStopped()) {
            try {
                // 从队列中,拿一个pullRequest (如果队列为空,则阻塞.)      executePullRequestImmediately(pullRequest) 方法中,向这个队列中put数据.
                PullRequest pullRequest = this.pullRequestQueue.take();
                // 拉消息
                this.pullMessage(pullRequest);
            } catch (InterruptedException ignored) {
            } catch (Exception e) {
                log.error("Pull Message Service Run Method exception", e);
            }
        }

        log.info(this.getServiceName() + " service end");
    }

    @Override
    public void shutdown(boolean interrupt) {
        super.shutdown(interrupt);
        ThreadUtils.shutdownGracefully(this.scheduledExecutorService, 1000, TimeUnit.MILLISECONDS);
    }

    @Override
    public String getServiceName() {
        return PullMessageService.class.getSimpleName();
    }

}
